<template>
  <div class="e-tabs">
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 动态参数面板 -->
    <el-tab-pane label="动态参数" name="many" >
                    <el-button type='primary' size='small' :disabled='isDisabled'  @click="showAddDialogVisible = true">添加参数</el-button>
            <!-- 表格 -->
               <el-table
               border
      :data="manyTableData"
      style="width: 100%">
       <el-table-column
        type="expand"
        >
          <template #default='{row}'>
                <el-tag v-for="(item,index) in row.attr_vals" :key="index" closable @close='deleteAttr(row,index)'>{{item}}</el-tag>
                <el-input
  class="add-input"
  v-if="row.inputVisible"
  v-model="row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(row,$event)"
  @blur="handleInputConfirm(row,$event)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small"  @click="showInput(row)">+ New Tag</el-button>
       </template>
      </el-table-column>
      <el-table-column
        type="index"
        label='#'
        >
      </el-table-column>
      <el-table-column
        prop="attr_name"
        label="参数名称"
        >
      </el-table-column>
      <el-table-column       
        label="操作">
         <template #default="{row}">
            <!-- 修改按钮 -->
            <el-button  type="primary" icon="el-icon-edit" size="mini" @click="showEditDia(row)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button  type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(row)">删除</el-button>
          </template>
      </el-table-column>
    </el-table>
    </el-tab-pane>
            <!-- 静态属性面板 -->
    <el-tab-pane label="静态属性" name="only">
                    <el-button type='primary' size='small' :disabled='isDisabled' @click="showAddDialogVisible = true">添加属性</el-button>
                              <el-table
               border
      :data="onlyTableData"
      style="width: 100%;"
      height='350px'>
       <el-table-column
        type="expand"
        >
       <template #default='{row}'>
                <el-tag v-for="(item,index) in row.attr_vals" :key="index" closable @close='deleteAttr(row,index)'>{{item}}</el-tag>
                <el-input
  class="add-input"
  v-if="row.inputVisible"
  v-model="row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(row,$event)"
  @blur="handleInputConfirm(row,$event)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small"  @click="showInput(row)">+ New Tag</el-button>
       </template>
      </el-table-column>
      <el-table-column
        type="index"
        label='#'
        >
      </el-table-column>
      <el-table-column
        prop="attr_name"
        label="参数名称"
        >
      </el-table-column>
      <el-table-column       
        label="操作">
         <template #default="{row}">
            <!-- 编辑按钮 -->
            <el-button  type="primary" icon="el-icon-edit" size="mini" @click="showEditDia(row)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button  type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(row)">删除</el-button>
          </template>
      </el-table-column>
    </el-table>
    </el-tab-pane>
  </el-tabs>
  <!-- 两个tabs公用一个对话框 -->
  <el-dialog
  :title="tipTitle"
  :visible.sync="showAddDialogVisible"
  width="50%"
   @close="resetAddForm"
    >
 <el-form :model="addForm" ref="addForm" label-width="100px">
  <el-form-item
    :label="labelText"
    prop="attr_name"
    :rules="[
      { required: true, message:'参数或属性不能为空',trigger:'blur'},
    ]"
  >
    <el-input type="text" v-model="addForm.attr_name"></el-input>
  </el-form-item>
</el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="showAddDialogVisible = false">取 消</el-button>
    <!-- 提交添加的属性 -->
    <el-button type="primary" @click="submitAttr" >确 定</el-button>
  </span>
</el-dialog>
<!-- 编辑对话框 -->
 <el-dialog
 @close='resetEditForm'
  title="编辑参数或属性"
  :visible.sync="showEditDialogVisible"
  width="50%"
    >
 <el-form :model="editForm" ref="editForm" label-width="100px">
  <el-form-item
    label="编辑参数"
    prop="attr_name"
    :rules="[
      { required: true, message:'参数或属性不能为空',trigger:'blur'},
    ]"
  >
    <el-input type="text" v-model="editForm.attr_name"></el-input>
  </el-form-item>
</el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="showEditDialogVisible = false">取 消</el-button>
    <!-- 提交添加的属性 -->
    <el-button type="primary" @click="submitEdit">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import {getCategoryParmasByAxios,addParamsByAxios,editParamsByAxios,deleteCategoryParamsByAxios} from 'network/axios'
export default {    
        name:'Etabs',
        props:{
                isDisabled:{
                    type:Boolean,
                    default:true
                },
                cateId:{
                    required:true
                }
        },
        data(){
            return{
                //当前活跃的面板
                activeName:'many',
                //动态参数数据
                manyTableData:[],
                //静态参数数据
                onlyTableData:[],
                //添加属性对话框的显示与隐藏
                showAddDialogVisible:false,
                //表单数据
                addForm:{
                    attr_name:''
                },
                //编辑对话框的显示与隐藏
                showEditDialogVisible:false,
                //编辑对话框中的表单数据
                editForm:{
                    attr_name:'',
                    cate_Id:'',
                    attr_id:'',
                    oldAttrName:''
                },
              
        
            }
        },
        methods:{
            handleTabClick(){
              if(this.cateId===null||this.cateId===0){
                return
              }
                 this.getCategoryParams()
            },
            resetAddForm(){
                this.$refs.addForm.resetFields()
            },
            submitAttr(){
                this.$refs.addForm.validate(flag=>{
                    if(!flag){
                        this.$message.error('请根据提示输入有效的信息')
                    }else{
                                addParamsByAxios({
                    name:this.addForm.attr_name,
                    sel:this.activeName,
                    id:this.cateId
                }).then(res=>{
                    if(res.data.meta.status!=201){
                        this.$message.error('添加属性或参数失败!')
                    }else{
                        this.getCategoryParams()
                        this.showAddDialogVisible=false
                        this.$message.success('添加属性或参数成功')
                    }
                })
                    }
                })
            
            },
            //封装获取分类列表
            getCategoryParams(){
                   getCategoryParmasByAxios({
                    id:this.cateId,
                    sel:this.activeName
                }).then(res=>{
                    console.log(res.data.data);
                    res.data.data.forEach(element => {
                        element.inputValue=''
                        element.inputVisible=false
                        element.attr_vals=element.attr_vals?element.attr_vals.split(" "):[]
                    });
                    console.log(res); 
                    if(this.activeName==='many'){
                        this.manyTableData=res.data.data
                    }else
                    this.onlyTableData=res.data.data

                })
            },
            showEditDia(row){
                console.log(row);
                this.editForm.attr_name=row.attr_name
                this.editForm.cate_Id=row.cat_id
                this.editForm.attr_id=row.attr_id
                this.editForm.oldAttrName=row.attr_name
                this.showEditDialogVisible=true
            },
        //点击提交表单,先验证表单输入内容是否合法,然后看输入内容有没有修改,最后在提交请求
            submitEdit(){
                this.$refs.editForm.validate(flag=>{
                    if(!flag){
                        this.$message.error('请根据提示输入有效的信息')
                    }else{
                        if(this.editForm.attr_name===this.editForm.oldAttrName)
                        return this.$message.warning('您并没有做过任何修改')
                        editParamsByAxios({
                            cateId:this.editForm.cate_Id,
                            attrId:this.editForm.attr_id,
                            name:this.editForm.attr_name,
                            sel:this.activeName
                        }).then(res=>{
                            if(res.data.meta.status!=200)
                                      return  this.$message.success('更新失败')                              
                             this.$message.success('更新成功')
                             this. getCategoryParams()
                             this.showEditDialogVisible=false

                        })
                    }
                })
            },
            //关闭编辑表单对话框重置表单
            resetEditForm(){
                this.$refs.editForm.resetFields()
            },
            //删除属性
          deleteParams(row){
              this.$confirm("删除之后不可恢复,确定要此属性吗?", "确认信息", {
        confirmButtonText: "确认删除",
        cancelButtonText: "点错了",
      }).then(() => {
             deleteCategoryParamsByAxios({
                    cateId:row.cat_id,
                    attrId:row.attr_id
                }).then(res=>{
                    if(res.data.meta.status!=200)
                    return this.$message.error('删除失败')
                    this.getCategoryParams()
                    this.$message.success('删除成功')
                })
        }).catch(() => {
          this.$message("您取消了删除操作");
        })     
      },
      //标签输入框是去焦点或者按回车触发的事件,这里按回车后,还会同时触发是去焦点事件,所以要处理一下
      handleInputConfirm(row,event){
          console.log(row.inputValue);
          console.log(event);
          //防止回车的时候又触发是去焦点事件,干脆直接回车不触发后面的事件
          if(event.key==='Enter'){
            row.inputVisible=false
            return
          }
         
            if(row.inputValue.trim()==='')
           {
             this.$message.warning('您并没有输入任何内容')
             row.inputVisible=false
             row.inputValue=''
           }else{
               row.attr_vals.push(row.inputValue.trim())
                row.inputVisible=false
               editParamsByAxios({
                 cateId:this.cateId,
                 attrId:row.attr_id,
                  name:row.attr_name,
                sel:row.attr_sel,
                vals:row.attr_vals.join(' ')
               }).then(res=>{
                const{data}=res
                if(data.meta.status!=200){
                      this.$message.error('添加失败')
                      row.inputValue=''
                }else{
                  this.$message.success('添加成功')
                  row.inputValue=''
                }
               })
           }
      },
      // 对话框的显示
     showInput(row) {
        row.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
    deleteAttr(row,index){
          row.attr_vals.splice(index,1)
          editParamsByAxios({
                 cateId:this.cateId,
                 attrId:row.attr_id,
                  name:row.attr_name,
                sel:row.attr_sel,
                vals:row.attr_vals.join(' ')
               }).then(res=>{
                const{data}=res
                if(data.meta.status!=200){
                      this.$message.error('修改失败')
                      row.inputValue=''
                }else{
                  this.$message.success('修改成功')
                  row.inputValue=''
                }
               })
    }
        },
        watch:{
            //监听父组件的id有没有变化,有变化说明用户切换了分类,就要重新发送网络请求重新渲染页面
            cateId(newvalue){
                  if(newvalue===null||newvalue==0){
                    this.manyTableData=[]
                    this.onlyTableData=[]
                    return
                  }
                getCategoryParmasByAxios({
                    id:newvalue,
                    sel:this.activeName
                }).then(res=>{
                    res.data.data.forEach(element => {
                      element.inputValue=''
                      element.inputVisible=false
                        element.attr_vals=element.attr_vals?element.attr_vals.split(" "):[]
                    })
                    if(this.activeName==='many'){
                        this.manyTableData=res.data.data
                    }else
                    this.onlyTableData=res.data.data

                })
            }
        },
        computed:{
            //对话框左上角提示文字
            tipTitle(){
                if(this.activeName==='many')
                return "添加动态参数"
                return "添加静态属性"
            },
                labelText(){
                     if(this.activeName==='many')
                return "动态参数"
                return "静态属性"
                }
        },
        
}
</script>

<style scoped>
        .el-table{
            margin-top: 10px;
            font-size: 12px;
        }
        .el-tabs{
            font-size: 12px;
        }
        .el-tag{
            margin: 20px;
        }
        .add-input{
          width: 100px;
        }
</style>